package com.servlets.user;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.GlobalConstants;
import com.core.ListUtils;
import com.core.RequestParams;
import com.core.protocols.IKVObject;
import com.core.protocols.IServiceLayerDelegate;
import com.model.mapparser.UserMapParser;
import com.model.user.User;
import com.servicelayer.user.UserListLayer;
import com.servlets.TaskTrackerServlet;

/**
 * Servlet implementation class ProjectAdd
 */
public class UserAdd
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {

    private HttpServletResponse postResponse     = null;

    private static final long   serialVersionUID = 1L;



    public UserAdd() {

    }



    @Override
    protected void doPost ( HttpServletRequest request,
                            HttpServletResponse response )
            throws ServletException, IOException {

        this.postResponse = response;

        RequestParams requestParams = RequestParams.paramsFromRequest(request);
        User template = UserMapParser.fromMap(requestParams);



        UserListLayer userListLayer = new UserListLayer();
        userListLayer.setLayerDelegate(this);

        try {
            IServiceLayerDelegate delegate = userListLayer.getLayerDelegate();
            UserListLayer.createEntityWithTemplate(template, delegate, null);
        } catch ( Exception e ) {

        }


    }



    @Override
    public <T> void responseResponseItemsList ( final List <T> items,
                                                final Object request,
                                                final Exception exception ) {

        T item = ListUtils.listItemAtIndex(items, 0);

        this.redirectItemIntoOpenServlet(item);

    }



    private <T> void redirectItemIntoOpenServlet ( T item ) {

        if ( this.postResponse == null ) {
            return;
        }

        String redirection = String.format("%s", GlobalConstants.SERVLET_PROJECTLIST);

        if ( item != null ) {
            if ( item instanceof IKVObject ) {
                IKVObject kvObject = (IKVObject) item;
                String idValue = kvObject.idValue().toString();
                redirection = String.format("%s?%s", GlobalConstants.SERVLET_USERINFO, idValue);
            }
        }

        try {
            this.postResponse.sendRedirect(redirection);
        } catch ( IOException e ) {
            e.printStackTrace();
        }

    }

}
